package com.example.redistest.redispackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * \* @author: wky
 * \* Date: 2022/10/08
 * \* Time: 18:25
 * \* To change this template use File | Settings | File Templates.
 * \* Description:RedisCache
 * \
 */
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        long startTime = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, value);
        System.out.println("setCacheObject 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        long startTime = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
        System.out.println("setCacheObject 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        boolean ret = false;
        long startTime = System.currentTimeMillis();
        ret = expire(key, timeout, TimeUnit.SECONDS);
        System.out.println("expire 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return ret;
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        boolean ret = false;
        long startTime = System.currentTimeMillis();
        ret = redisTemplate.expire(key, timeout, unit);
        System.out.println("expire 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return ret;
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        long startTime = System.currentTimeMillis();
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        System.out.println("getCacheObject 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        boolean ret = false;
        long startTime = System.currentTimeMillis();
        ret = redisTemplate.delete(key);
        System.out.println("deleteObject 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return ret;
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        long count = 0;
        long startTime = System.currentTimeMillis();
        count = redisTemplate.delete(collection);
        System.out.println("deleteObject 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return count;
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = null;
        long startTime = System.currentTimeMillis();
        count = redisTemplate.opsForList().rightPushAll(key, dataList);
        System.out.println("setCacheList 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
        List<T> list = null;
        long startTime = System.currentTimeMillis();
        list = redisTemplate.opsForList().range(key, 0, -1);
        System.out.println("getCacheList 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return list;
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = null;
        long startTime = System.currentTimeMillis();
        setOperation = redisTemplate.boundSetOps(key);
        System.out.println("setCacheSet 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        Set<T> sets = null;
        long startTime = System.currentTimeMillis();
        sets = redisTemplate.opsForSet().members(key);
        System.out.println("getCacheSet 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return sets;
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            long startTime = System.currentTimeMillis();
            //redisTemplate.opsForHash().putAll(key, dataMap);
            redisTemplate.boundHashOps(key).putAll(dataMap);
            System.out.println("setCacheMap 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        Map<String,T> map = null;
        long startTime = System.currentTimeMillis();
        map = redisTemplate.boundHashOps(key).entries();
        System.out.println("getCacheMap 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return map;
        //return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        long startTime = System.currentTimeMillis();
        //redisTemplate.opsForHash().put(key, hKey, value);
        redisTemplate.boundHashOps(key).put(hKey,value);
        System.out.println("setCacheMapValue 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        BoundHashOperations<String, String, T> hashOperations = null;
        long startTime = System.currentTimeMillis();
        hashOperations = redisTemplate.boundHashOps(key);
        System.out.println("getCacheMapValue 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return hashOperations.get(hKey);
        /*HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);*/
    }

    /**
     * 删除Hash中的数据
     *
     * @param key
     * @param hkey
     */
    public boolean delCacheMapValue(final String key, final String hkey)
    {
        try{
            Long count = null;
            long startTime = System.currentTimeMillis();
            count = redisTemplate.boundHashOps(key).delete(hkey);
            System.out.println("delCacheMapValue 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
            return count>0;
        }catch (Exception e) {
            return false;
        }

        /*HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);*/
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        List<T> list = null;
        long startTime = System.currentTimeMillis();
        list = redisTemplate.boundHashOps(key).multiGet(hKeys);
        System.out.println("getMultiCacheMapValue 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return list;
        //return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        Collection<String> collection = null;
        long startTime = System.currentTimeMillis();
        collection = redisTemplate.keys(pattern);
        System.out.println("keys 执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return collection;
    }

    /**
     * 执行管道
     * @param map
     * @return
     */
    public <T> List<T> executePipelinedWrite(Map<String,T> map) {

        List<T> objects = null;
        long startTime = System.currentTimeMillis();
        objects = redisTemplate.executePipelined(new SessionCallback() {
                @Override
                public Object execute(RedisOperations opt) throws DataAccessException {
                    RedisTemplate<String, Object> template = (RedisTemplate<String, Object>) opt;
                    ValueOperations<String, Object> operations = template.opsForValue();
                    Set<String> keys = map.keySet();
                    for(String key : keys) {
                        operations.set(key,map.get(key));
                    }
                    return null;
                }
            }
        );
        System.out.println("executePipelinedWrite 写管道执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        return objects;
    }

    /**
     *
     * @param keys
     * @param <T>
     * @return
     */
    public <T> Map<String,T> executePipelinedRead(List<String> keys) {

        List<T> objects = null;
        long startTime = System.currentTimeMillis();
        objects = redisTemplate.executePipelined(new SessionCallback() {
                 @Override
                 public Object execute(RedisOperations opt) throws DataAccessException {
                     RedisTemplate<String, Object> template = (RedisTemplate<String, Object>) opt;
                     ValueOperations<String, Object> operations = template.opsForValue();
                     for(String key : keys) {
                         operations.get(key);
                     }
                     return null;
                 }
             }
        );
        System.out.println("executePipelinedRead 读管道执行用时: " + (System.currentTimeMillis() - startTime) + " ms");
        Map<String,T> map = new HashMap<>();
        for(int i=0;i<keys.size();i++) {
            map.put(keys.get(i),objects.get(i));
        }
        return map;
    }

}